<template>
	<div>
        <div v-if="isShow">
            <TopFilter
            :list="formList"
            :cols="3"
            @filterChange="filterChangeHandle"
            @onCollapse="collapseHandle"
            ></TopFilter>
            <FilterTable
            ref="table"
            :columns="columns"
            :fetchapi="fetchApi"
            :params="fetchParams"
            :datakey="'records'"
            :isSelectColumn="false"
            :onColumnsChange="columns => this.columns = columns"
            >
            <template slot="controls" >
                <el-button size="small" type="primary"  @click="addHandle()">新增</el-button>
            </template>
            </FilterTable>
        </div>

        <div v-else style="background:#fff;">
            <FormPanel 
            ref="FormPanel" 
            :cols="4" 
            labelWidth="120"
            :list="formList2" 
            :formType="formType" 
            :isSubmitBtn="false" 
             />
            
            <FilterTable
            ref="table"
            :columns="columns2"
            :dataSource="dataSource"
            height="auto"
            :isSelectColumn="false"
            :onColumnsChange="columns => this.columns = columns"
            >
            <!-- <template slot="controls" slot-scope="props">
                <el-button size="small" type="primary" icon="el-icon-plus" @click="addHandle2()">新增</el-button>
            </template> -->
            </FilterTable>
            <div style="text-align: center;margin:10px 0">
                <el-button size="small" type="primary"  @click="saveHandle()">保存</el-button>
                <el-button size="small"   @click="closeHandler()">关闭</el-button>
            </div>
        </div>
		<BaseDialog
      :visible.sync="dialogVisible"
      title="整车退单-原单搜索"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <vRModal @addDialogHandle="addDialogHandle"  @close="close" />
    </BaseDialog>
	</div>
</template>

<script>
import { listReturnOrders,insertReturnSales,getReturnOrdersById,cancelReturnSales,submitReturnSales} from '@/api/retail/salesmanage/vehicleReturn';
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
import { phone } from '@/utils/validate'
import vRModal from './vRModal'

export default {
	name: 'vehicleReturn',
	mixins: [dictionary],
	components: {
	  vRModal
	},
	data() {
    return {
        formList: this.createFormList(),
        columns: this.createTableColumns(),
        fetchApi: listReturnOrders,
        fetchParams: {},
        formList2: this.createFormList2(),
        columns2: this.createTableColumns2(),
        fetchApi2: null,
        fetchParams2: {},
        isShow: true,
        formType:null,
        dialogVisible:false,
        salesVinId:"",
        soNoId:"",
        dataSource:[],
        recordVersion:"",
    }
  },
	methods: {
		createFormList() {
	      return [
	        {
	          type: 'INPUT',
	          label: '退回单号',
	          fieldName: 'salesReturnNo',
	          placeholder: '请输入...',
	        },
          {
	          type: 'INPUT',
	          label: '销售顾问',
	          fieldName: 'consultantId',
	          placeholder: '请输入...',
	        },
            {
	          type: 'INPUT',
	          label: '客户名称',
	          fieldName: 'customerName',
	          placeholder: '请输入...',
	        },
            {
	        type: 'RANGE_DATE',
	        label: '退单日期',
	        fieldName: 'salesReturnDateStart|salesReturnDateEnd',
	        placeholder: '请选择日期...'
	        }
          // {
	        //   type: 'SELECT',
	        //   label: '配车状态',
	        //   fieldName: 'dispatchedStatus',
	        //   placeholder: '请选择...',
	        //   itemList: this.createDictList('1414').filter(x => [14141001,14141002].includes(x.value))
	        // },
	      ];
	    },
      createTableColumns (){
        return [
          {
            title: '操作',
            dataIndex: 'column-action',
            width: 140,
            fixed: 'left',
            render: (props, h) => {
              return (
                <div>
                <el-button  size="mini" type="text" onClick={() => this.editHandle(props.row)}>编辑</el-button>
                <el-button  size="mini" type="text" onClick={() => this.deleteHandle(props.row)}>删除</el-button>
                <el-button  size="mini" type="text" onClick={() => this.subHandle(props.row)}>提交</el-button>
                </div>
              );
            }
          },
          {
            title: '序号',
            dataIndex: 'index',
            width: 80,
            sorter: true,
            render: props => {
              return <span>{props.row.index + 1}</span>;
            }
          },
          {
            title: '退回单号',
            dataIndex: 'soNo',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: '原销售单号',
            dataIndex: 'soNo',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: '客户编号',
            dataIndex: 'customerNo',
            sorter: true,
            filter: true,
            filterType: 'input',
            /* filterItems: this.createDictList('1404'),
            render: props => {
              return <span>{this.createDictText(props.row.viStatus, '1404')}</span>;
            } */
          },
          {
            title: '客户名称',
            dataIndex: 'customerName',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: '销售顾问',
            dataIndex: 'consultantName',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: '退车状态',
            dataIndex: 'soStatus',
            sorter: true,
            filter: true,
            filterType: 'input',
            filterItems: this.createDictList('1404'),
            render: props => {
              return <span>{this.createDictText(Number(props.row.soStatus), '1404')}</span>;
            }
          },
          {
            title: '退车原因',
            dataIndex: 'returnReason',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: '退车申请日期',
            dataIndex: 'sheetCreateDate',
            sorter: true,
            filter: true,
            filterType: 'input',
            /* render: props =>{
              return <span>{ this.formatDates(props.row.modelName) } </span>
            } */
          },
          {
            title: '产品名称',
            dataIndex: 'productName',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: '产品代码',
            dataIndex: 'productNo',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: 'VIN',
            dataIndex: 'vin',
            sorter: true,
            filter: true,
            filterType: 'input',
            
          },
          {
            title: '品牌',
            dataIndex: 'brandName',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: '车系',
            dataIndex: 'seriesName',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: '车型',
            dataIndex: 'modelName',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: '销售单价',
            dataIndex: 'salesPrice',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: '成本单价',
            dataIndex: 'costPrice',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: '生产日期',
            dataIndex: 'createDate',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          /* {
            title: '防盗螺栓号',
            dataIndex: 'brandName11',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: '收音机密码',
            dataIndex: 'seriesName22',
            sorter: true,
            filter: true,
            filterType: 'input',
          }, */
          {
            title: '备注',
            dataIndex: 'remark',
            sorter: true,
            filter: true,
            showOverflowTooltip:true,
            filterType: 'input',
          },

        ]
      },

    //   2
    createFormList2() {
	      return [
	        {
	          type: 'INPUT',
	          label: '原销售单号',
	          fieldName: 'oldSoNo',
            placeholder: '请输入...',
            readonly:true,
            unitRender: () => {
              return <el-button slot="append" icon="el-icon-search" onClick={this.openDriveCancel}></el-button>;
            },
              rules: [{ required: true, message: '请选择原销售单号', trigger: 'blur' }]
	        },
            {
	          type: 'INPUT',
	          label: '销售顾问',
	          fieldName: 'consultantName',
            placeholder: '请输入...',
            disabled:true,
            },
            {
            type: 'DATE',
            label: '退单日期',
            fieldName: 'returnDate',
            dateType:"date",
            placeholder: '请选择日期...',
            },
            {
	          type: 'INPUT',
	          label: '退回单号',
	          fieldName: 'salesReturnNo',
            placeholder: '请输入...',
            disabled:true,
            },
            {
	          type: 'INPUT',
	          label: '客户名称',
	          fieldName: 'customerName',
            placeholder: '请输入...',
            disabled:true,
	        },
            {
	          type: 'INPUT',
	          label: '新车销售类型',
	          fieldName: 'salesType',
            placeholder: '请输入...',
            disabled:true,
            /* validator: phone, */
            // rules: [{ required: true, message: '请输入新车销售类型', trigger: 'blur' }]
            },
            {
	          type: 'INPUT',
	          label: '退车原因',
	          fieldName: 'returnReason',
            placeholder: '请输入...',
            },
            {
            type: 'TEXT_AREA',
            label: '备注',
            fieldName: 'remark',
            placeholder: '请选择',
            selfCols: 2,
            // style: { width: '232%' }
            },
	      ];
	    },
      createTableColumns2 (){
        return [
          /* {
            title: '操作',
            dataIndex: 'column-action',
            width: 140,
            fixed: 'left',
            render: (props, h) => {
              return (
                <div>
                <el-button  size="mini" type="text" onClick={() => this.editHandle(props.row)}>编辑</el-button>
                <el-button  size="mini" type="text" onClick={() => this.deleteHandle(props.row)}>删除</el-button>
                <el-button  size="mini" type="text" onClick={() => this.subHandle(props.row)}>提交</el-button>
                </div>
              );
            }
          }, */
          {
            title: '序号',
            dataIndex: 'index',
            width: 80,
            sorter: true,
            render: props => {
              return <span>{props.row.index + 1}</span>;
            }
          },
          {
            title: '产品代码',
            dataIndex: 'productNo',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: 'VIN',
            dataIndex: 'salesVin',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: '发动机号',
            dataIndex: 'engineNo',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: '合格证书',
            dataIndex: 'soNo',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: '产品名称',
            dataIndex: 'productName',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: '生产日期',
            dataIndex: 'createDate',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: '销售单价',
            dataIndex: 'salesPrice',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: '税额',
            dataIndex: 'costPrice1',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: '不含税单价',
            dataIndex: 'unTaxPrice',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
          {
            title: '成本单价',
            dataIndex: 'costPrice',
            sorter: true,
            filter: true,
            filterType: 'input',
          },
        ]
      },
	      filterChangeHandle (val){ //搜索
            this.fetchParams = Object.assign({}, val)
        },
        collapseHandle() {
          this.$nextTick(() => {
            this.BaseTable.EXECUTE_RESET_HEIGHT();
          });
        },
        subHandle (val){ //提交事件
            console.log(val,'提交事件')
            let params={
              "recordVersion": val.recordVersion,
              "remark": val.remark,
              "returnDate": val.returnDate,
              "returnReason": val.returnReason,
              "salesVinId": val.soVinId,
              "soNoId": val.soNoId
            }
            submitReturnSales(params).then(res=>{
              if(res.success){
                this.$message({
                  showClose: true,
                  message: '提交成功',
                  type: 'success'
                });
                // 重新加载
                this.fetchParams = { ...this.fetchParams };
              }
            })
        },
        editHandle (val){ //编辑事件
            console.log(val)
            this.handleType = 'edit'
            this.formData = val;
            this.isShow=false

            this.dataSource.push(this.formData)
            this.dataSource.forEach((x,k)=>{
              x.index = k
            })
            this.formList2.forEach(x=>{
              x.initialValue = this.formData[x.fieldName]
            })
            this.salesVinId = this.formData.soVinId
            this.soNoId = this.formData.soNoId
            this.recordVersion = this.formData.recordVersion
        },
        addHandle (){ //编辑事件
            // console.log("编辑事件")
            this.isShow=false
        },
        deleteHandle(val){
          console.log(val,"val")
          this.open(val)
        },
        open(val) {
            this.$confirm(`你将要删除销售退单编号为：${val.soNo?val.soNo:""}位流水号,原销售单编号为：${val.vehiclesSum?val.vehiclesSum:""}位流水号的数据。继续吗？`, '提示', {
              confirmButtonText: '是',
              cancelButtonText: '否',
              type: 'warning'
            }).then(() => {
              cancelReturnSales(val.soNoId).then(res=>{
                if(res.success){
                    this.$message({
                      showClose: true,
                      message: '删除成功',
                      type: 'success'
                    });
                    // 重新加载
                    this.fetchParams = { ...this.fetchParams };
                }
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });          
            });
          },
        //保存
        saveHandle(){
          let data = this.$refs.FormPanel.SUBMIT_FORM()
          console.log(data,"datat",this.salesVinId,this.soNoId,this.recordVersion)
          if(data){
            let params ={
              ...data,
              salesVinId:this.salesVinId?this.salesVinId:"",
              soNoId:this.soNoId?this.soNoId:"",
              recordVersion: this.recordVersion?this.recordVersion:"",
            }
            insertReturnSales(params).then(res=>{
              if(res.success){
                console.log(res,"insertReturnSales")
                this.closeHandler('refresh')
              }
            })
          }
        },
        //原单销售单号
        openDriveCancel(val){
            // console.log(val,"val")
            this.dialogVisible=true
            this.formList2.find(x=>x.fieldName == 'oldSoNo').initialValue =""
        },
        //原单保存
        async addDialogHandle(val,row){
            // console.log(val,"val",row)
            this.dataSource=[]
            await getReturnOrdersById(row[0].soVinId).then(res=>{
              if(res.success){
                console.log(res,"元旦数据")
                this.dataSource.push(res.data)
                this.dataSource.forEach((x,k)=>{
                  x.index = k
                })
                this.formList2.forEach(x=>{
                  x.initialValue = res.data[x.fieldName]
                })
                this.salesVinId = res.data.soVinId
                this.soNoId = res.data.soNoId
                this.recordVersion = res.data.recordVersion
              }
            })

            this.formList2.find(x=>x.fieldName == 'oldSoNo').initialValue = val
            this.close()
        },
        //原单取消
        close() {
            this.dialogVisible = false;
            // 重新加载
            this.fetchParams = { ...this.fetchParams };
        },
        formatDates (value) { //时间过滤
            // 这里的 value 就是需要过滤的数据
            if (value == null || value == "") {
            return "";
            }
            var date = new Date(Number(value));
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var day = date.getDate();
            return year + "-" + month + "-" + day;
        },
        closeHandler(val, type) {
            this.isShow = true;
            if (type === 'refresh') {
            // 重新加载
            this.fetchParams = { ...this.fetchParams };
            }

            this.formList2.forEach(x=>{
              x.initialValue = ""
            })
            this.salesVinId = ""
            this.soNoId = ""
            this.recordVersion =""
        }
	}
}
</script>

<style scoped="scoped" lang="less">

.bottom_center{
	text-align: center;
	margin: 15px 0;
}
</style>
